﻿using System;
using System.Configuration;
using ApiScanner.Core;

namespace ApiScannerShell
{
    public sealed class MainModel
    {
        private bool _IsNew;
        private Configuration _ConfigurationManager;

        public MainModel(string filename)
        {
            if (string.IsNullOrEmpty(filename)) throw new ArgumentNullException("filename");

            FileName = filename;

            CreateConfiguratonManager();
            Configuration = ScannerConfigurationSection.Open(_ConfigurationManager);

        }

        private void CreateConfiguratonManager()
        {
            _ConfigurationManager = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap {ExeConfigFilename = FileName}, ConfigurationUserLevel.None);
        }

        public MainModel()
        {
            Configuration = new ScannerConfigurationSection();
            _IsNew = true;
        }

        public string FileName { get; set; }
        public ScannerConfigurationSection Configuration { get; private set; }

        public void Save()
        {
            _ConfigurationManager.Save();
        }
        public void SaveAs()
        {
            if (_ConfigurationManager == null)
            {
                CreateConfiguratonManager();
                _ConfigurationManager.Sections.Clear();
                Configuration.RegisterOnConfiguration(_ConfigurationManager);
                _ConfigurationManager.Save();
            }
            else
            {
                _ConfigurationManager.SaveAs(FileName);
            }
        }
    }
}